package com.ruoyi.web.controller.project;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 审核Controller
 *
 * @author Edward
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/project/checkList")
public class CheckListController extends BaseController {
    @Autowired
    private ICheckListService checkListService;

    @Autowired
    private IDemandService demandService;

    @Autowired
    private ITopicService topicService;

    @Autowired
    private IAwardsService awardsService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IAwardsRuleService iAwardsRuleService;

    @Autowired
    private UserProjectService userProjectService;

    @Autowired
    private IPointsLogService pointsLogService;

    @Autowired
    private IPointsDeptLogService pointsDeptLogService;

    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private SysDeptServiceImpl sysDeptServiceImpl;


    /**
     * 查询审核列表
     */
    @PreAuthorize("@ss.hasPermi('project:check:list')")
    @GetMapping("/list")
    public TableDataInfo list(CheckList checkList) {
        startPage();
        Long userId = getUserId();
        List<CheckList> list = new ArrayList<>();
        if (userId == 1) {
            list = checkListService.selectCheckListList(checkList);
        } else {
            list = checkListService.selectCheckListByCheckerId(userId);
        }
        return getDataTable(list);
    }

    /**
     * 导出审核列表
     */
    @PreAuthorize("@ss.hasPermi('project:check:export')")
    @Log(title = "审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheckList checkList) {
        List<CheckList> list = checkListService.selectCheckListList(checkList);
        ExcelUtil<CheckList> util = new ExcelUtil<CheckList>(CheckList.class);
        util.exportExcel(response, list, "审核数据");
    }

    /**
     * 获取审核详细信息
     */
    //@PreAuthorize("@ss.hasPermi('project:check:query')")
    @GetMapping(value = "/seeCheck/{id}")
    public AjaxResult seeCheck(@PathVariable("id") Long id) {
        Project project = demandService.selectProjectById(id);
        CheckList check = new CheckList();
        check.setProjectId(id);
        check.setState(project.getState());
        System.out.println("状态：" + check.getState());
        if (project.getType() == 3) {
            CheckList checkList = new CheckList();
            checkList.setCheckerName("审核未通过");
            return success(checkList);
        }
        check.setType(project.getType());
        check = checkListService.seeCheck(check);
        if (check == null) {
            CheckList checkList = new CheckList();
            checkList.setCheckerName("当前未审核");
            return success(checkList);
        } else {
            return success(check);
        }
    }

    /**
     * 获取审核详细信息
     */
    //@PreAuthorize("@ss.hasPermi('project:check:query')")
    @GetMapping(value = "/seeClaimCheck/{id}")
    public AjaxResult seeClaimCheck(@PathVariable("id") Long id) {
        CheckList check = new CheckList();
        check.setProjectId(id);
        check.setType(4);
        check = checkListService.seeClaimCheck(check);
        if (check == null) {
            CheckList checkList = new CheckList();
            checkList.setCheckerName("当前未审核");
            return success(checkList);
        } else {
            return success(check);
        }
    }


    /**
     * 获取审核详细信息
     */
    //@PreAuthorize("@ss.hasPermi('project:check:query')")
    @GetMapping(value = "/seeAwardsCheck/{id}")
    public AjaxResult seeAwardsCheck(@PathVariable("id") Long id) {
        Awards awards = awardsService.selectAwardsById(id);
        CheckList check = new CheckList();
        check.setProjectId(id);
        check.setType(6);//6代表奖项申报类型
        check = checkListService.seeAwardsCheck(check);
        if (check == null) {
            CheckList checkList = new CheckList();
            checkList.setCheckerName("当前未审核");
            return success(checkList);
        } else {
            return success(check);
        }
    }


    /**
     * 获取审核详细信息
     */
    //@PreAuthorize("@ss.hasPermi('project:check:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(checkListService.selectCheckListById(id));
    }

    /**
     * 新增审核
     * 0:成员1 ：需求 2：课题 3：成果 4，认领需求，5成员加入队伍 6奖励审核
     */
    @PreAuthorize("@ss.hasPermi('project:check:add')")
    @Log(title = "审核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheckList checkList) {
        return toAjax(checkListService.insertCheckList(checkList));
    }


    /**
     * 修改审核
     */
    @PreAuthorize("@ss.hasPermi('project:check:edit')")
    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheckList checkList) {
        return toAjax(checkListService.updateCheckList(checkList));
    }

    /**
     * 删除审核
     */
    @PreAuthorize("@ss.hasPermi('project:check:remove')")
    @Log(title = "审核", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(checkListService.deleteCheckListByIds(ids));
    }

    /**
     * 审核操作
     * 0:成员 1：需求 2：课题 3：成果 4，认领需求，5成员加入队伍 6奖励审核
     */
    @PreAuthorize("@ss.hasPermi('project:check:doCheck')")
    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @PutMapping("/doCheck")
    public AjaxResult doCheck(@RequestBody CheckList check) {
        Integer checkResult = check.getCheckResult();
        int type = check.getType();
        long userId = getUserId();
        long projectId = check.getProjectId();
        //成员申请成为开发人员
        if (type == 0) {
            //审核开发人员
            return doCheckDeveloper(projectId, userId, checkResult, check);
        } else if (type == 1) {
            return doCheckDemand(projectId, userId, checkResult, check);
            //在研课题
        } else if (type == 2) {
            return doCheckTopic(projectId, userId, checkResult, check);
            //成果管理
        } else if (type == 3)
            return doCheckAchievement(projectId, userId, checkResult, check);
        else if (type == 4) {
            return doCheckClaimNeed(projectId, userId, checkResult, check);
        } else if (type == 5) {
            return doCheckJoinTeam(projectId, userId, checkResult, check);
        } else {
            //审核奖励积分
            return doCheckAwards(projectId, userId, checkResult, check);
        }
    }


    /**
     * 审核成员加入团队
     */
    private AjaxResult doCheckJoinTeam(long projectId, long userId, Integer checkResult, CheckList check) {
        Project project = demandService.selectProjectById(projectId);
        //获取当前登录用户id，作为审核者;
        int project_state = project.getState();
        if (project_state == 1) {
            //设置已审核
            check.setState(1);
            check.setCheckTime(new Date());
            check.setCheckerId(userId);
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setIsShow(1);
                project.setState(2);
            }
            int result = checkListService.updateCheckList(check);
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 5);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }
    }

    /**
     * 审核认领需求
     */
    private AjaxResult doCheckClaimNeed(long projectId, long userId, Integer checkResult, CheckList check) {
        Project project = demandService.selectProjectById(projectId);
        //获取当前登录用户id，作为审核者;
        int project_state = project.getState();
        if (project_state == 4) {
            check.setState(1);
            check.setCheckerId(userId);
            check.setCheckTime(new Date());
            int result = checkListService.updateCheckList(check);
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setIsShow(1);
                project.setState(2);
                project.setId(null);
                project.setType(2);
                topicService.insertProject(project);
            }
            project.setChecker(userId);
            demandService.updateProject(project);
            //审核成功
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 4);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }

    }

    //审核需求
    public AjaxResult doCheckDemand(Long projectId, Long userId, int checkResult, CheckList check) {
        System.out.printf("%s_%s_%s_%s", projectId, userId, checkResult, check.getId());
        Project need = demandService.selectProjectById(projectId);
        //获取当前登录用户id，作为审核者;
        int project_state = need.getState();
        if (project_state == 1) {
            check.setCheckTime(new Date());
            //项目负责人id
            Long user_id = need.getUserId();
            //0:admin 1:开发成员 2：普通用户
            //project state: 0新建 1待审核 2已审核 3不通过
            check.setUserId(user_id);
            check.setState(1);
            int result = checkListService.updateCheckList(check);
            Project project = demandService.selectProjectById(projectId);
            //不同意
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setIsShow(1);
                project.setState(2);
            }
            project.setChecker(userId);
            demandService.updateProject(project);
            //审核成功
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 1);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }

    }

    //审核在研课题
    public AjaxResult doCheckTopic(Long projectId, Long userId, int checkResult, CheckList check) {
        Project project = demandService.selectProjectById(projectId);
        int state = project.getState();
        if (state == 1) {
            //已审核
            check.setState(1);
            check.setUserId(userId);
            check.setCheckTime(new Date());
            int result = checkListService.updateCheckList(check);
            //不同意
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setIsShow(1);
                project.setState(2);
            }
            project.setChecker(userId);
            demandService.updateProject(project);
            //审核成功
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 2);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }


    }


    /**
     * 审核奖励
     */

    public AjaxResult doCheckAwards(Long projectId, Long userId, int checkResult, CheckList check) {

        // 1. 校验参数合法性
        if (projectId == null || userId == null || check == null) {
            return AjaxResult.error("参数无效");
        }
        // 2. 获取奖项信息
        Awards awards = awardsService.selectAwardsById(projectId);
        if (awards == null) {
            return AjaxResult.error("奖项信息不存在");
        }
        int state = awards.getState();
        // 3. 检查项目是否已审核
        if (state != 1) {
            return AjaxResult.error("审核失败, 该项目已审核");
        }
        // 4. 更新审核信息
        check.setState(1);
        check.setCheckTime(new Date());
        int result = checkListService.updateCheckList(check);
        if (result != 1) {
            return AjaxResult.error("审核信息更新失败");
        }
        long deptId = userService.getDeptId(userId);

        if (checkResult == 1) {
            //设置已审核状态
            awards.setState(2);
            int deptPoints = awards.getPoints();
            int userPoints = awards.getPoints();
            AwardsRule awardsRule = iAwardsRuleService.selectAwardsRuleById(awards.getAwardsId());
            Long awardsId = awards.getAwardsId();
            //部门年度检查
            if (awardsId == 7 || awardsId == 10 || awardsId == 11) {
                deptPoints = checkDeptPoints(awardsId, 2, deptPoints, deptId);
                //个人月上限10，部门月上限100
            } else if (awardsId == 13) {
                deptPoints = checkDeptPoints(awardsId, 1, deptPoints, deptId);
                userPoints = checkUserPoints(awardsId, userPoints, userId);
            }

            //申报奖项分数
            //加积分和进来了
            SysUser user = userService.selectUserById(awards.getUserId());
            user.setPoints(user.getPoints() + userPoints);
            userService.updateUser(user);
            SysDept dept = deptService.selectDeptById(deptId);
            dept.setDeptPoints(dept.getDeptPoints() + deptPoints);
            deptService.updateDeptPoints(userId, deptPoints);
            //记录
            PointsLog pointsLog = new PointsLog();
            pointsLog.setPointsDesc(check.getName());
            pointsLog.setCreateTime(new Date());
            pointsLog.setCreaterId(check.getCheckerId());
            pointsLog.setPoints(userPoints);
            pointsLog.setUserId(check.getUserId());
            pointsLog.setProjectId(projectId);
            pointsLogService.insertPointsLog(pointsLog);
            //部门积分
            PointsDeptLog pointsDeptLog = new PointsDeptLog();
            pointsDeptLog.setPointsDesc(check.getName());
            pointsDeptLog.setCreateTime(new Date());
            pointsDeptLog.setCreaterId(check.getCheckerId());
            pointsDeptLog.setPoints(deptPoints);
            pointsDeptLog.setDeptId(deptId);
            pointsDeptLog.setProjectId(projectId);
            pointsDeptLogService.insertPointsDeptLog(pointsDeptLog);
        } else {
            //审核不通过
            awards.setState(3);
        }
        // 7. 更新其他审核信息
        Map<String, Object> map = new HashMap<>();
        map.put("projectId", projectId);
        map.put("type", 6);
        map.put("needCheckId", check.getId());
        checkListService.updateOtherCheck(map);
        return AjaxResult.success("审核成功");
    }

    //type 1:检查月度   2:检查年度
    public int checkDeptPoints(Long awardsId, int type, int points, Long deptId) {
        return checkListService.checkDeptPoints(awardsId, type, points, deptId);
    }

    public int checkUserPoints(long awardsId, int points, Long userId) {
        return checkListService.checkUserPoints(awardsId, points, userId);
    }

    //审核成果
    public AjaxResult doCheckAchievement(Long projectId, Long userId, int checkResult, CheckList check) {
        Project project = demandService.selectProjectById(projectId);
        int state = project.getState();
        if (state == 1) {
            check.setState(1);
            check.setCheckTime(new Date());
            int result = checkListService.updateCheckList(check);
            //不同意
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setIsShow(1);
                project.setState(2);
            }
            project.setChecker(userId);
            demandService.updateProject(project);
            //审核成功
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 3);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }
    }


    /**
     * 审核成为开发成员/
     */
    public AjaxResult doCheckDeveloper(Long projectId, Long userId, int checkResult, CheckList check) {
        Project project = demandService.selectProjectById(projectId);
        int state = project.getState();
        if (state == 1) {
            //设置已审核
            check.setState(1);
            check.setCheckerId(userId);
            check.setCheckTime(new Date());
            int result = checkListService.updateCheckList(check);
            if (checkResult == 0) {
                project.setState(3);
            } else {
                project.setState(2);
                project.setChecker(userId);
                Long developerId = check.getUserId();
                Long[] userIds = new Long[1];
                userIds[0] = developerId;
                roleService.insertAuthUsers(2L, userIds);
                demandService.updateProject(project);
            }
            //审核成功
            if (result == 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", projectId);
                map.put("type", 0);
                map.put("needCheckId", check.getId());
                checkListService.updateOtherCheck(map);
                return AjaxResult.success("审核成功");
                //审核失败
            } else {
                return AjaxResult.error("审核失败");
            }
        } else {
            return AjaxResult.error("审核失败,该项目已审核");
        }
    }

    //审核项目（送审）
    @RequestMapping(value = "/addCheckProject")
    public AjaxResult addCheckProject(@RequestBody Project project) {
        project.setState(1);
        demandService.updateProject(project);
        //获取项目ID
        Long projectId = project.getId();
        String name = project.getName();
        int type = project.getType();
        Long userId = getUserId();
        checkListService.addTwoCheck(projectId, userId, type, name);
        return AjaxResult.success("送审成功");
    }

    //奖项（送审）
    @RequestMapping(value = "/addCheckAwards")
    public AjaxResult addCheckAwards(@RequestBody Awards awards) {
        awards.setState(1);
        awardsService.updateAwards(awards);
        checkListService.addCheckAwards(awards);
        return AjaxResult.success("送审成功");
    }


    //认领需求送审
    @RequestMapping(value = "/addClaimNeedCheck")
    public AjaxResult addClaimNeedCheck(@RequestBody Project project) {
        Long projectId = project.getId();
        Long userId = getUserId();
        Integer state = project.getState();
        String name = project.getName();
        int type = project.getType();
        if (state == 2 && type == 1) {
            project.setState(4);
            demandService.updateProject(project);
            checkListService.addTwoCheck(projectId, userId, 4, name);
            return AjaxResult.success("申请认领成功，等待审核");
        } else {
            return AjaxResult.error("认领失败，请确认项目状态");
        }
    }


    //申请加入团队
    @RequestMapping(value = "/addJoinForm")
    public AjaxResult addJoinForm(@RequestBody Project project) {
        String username = getUsername();
        project.setState(1);
        demandService.updateProject(project);
        Long projectId = project.getId();
        Long userId = getUserId();
        Integer isFull = project.getIsFull();
        Integer type = project.getType();
        if (isFull == 0 && type == 2) {//isFull=1团队满员状态
            checkListService.addTwoCheck(projectId, userId, 5, username);
            checkListService.addLeaderCheck(projectId, userId, 5, username);
            return AjaxResult.success("申请团队成功，等待审核");
        } else {
            return AjaxResult.error("申请失败，请确认项目状态");
        }
    }
}

